package com.xinyiweidai.xinyiweidai.module.my;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lan.mylibrary.okhttp.L;
import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.StringCallback;
import com.lan.mylibrary.ui.MyTextView;
import com.lan.mylibrary.ui.MyToast;
import com.xinyiweidai.xinyiweidai.Constants;
import com.xinyiweidai.xinyiweidai.R;
import com.xinyiweidai.xinyiweidai.base.BaseFragment;
import com.xinyiweidai.xinyiweidai.bean.PhoneBean;
import com.xinyiweidai.xinyiweidai.module.bind.BindingActivity;
import com.xinyiweidai.xinyiweidai.module.loan.PaymentActivity;
import com.xinyiweidai.xinyiweidai.module.login.LoginActivity;
import com.xinyiweidai.xinyiweidai.util.Api;
import com.xinyiweidai.xinyiweidai.util.SpUtil;

import java.util.HashMap;

import okhttp3.Request;

/**
 * classname: $CLASS_NAME$
 * Data：2018/9/20-10:47
 * Author: lanxiong
 * Description: 我的fragment
 */

public class MyFragment extends BaseFragment {


    private TextView tv_my_login;
    private RelativeLayout ll_after_login;
    private MyTextView tv_pay_now;
    private MyTextView tv_pay_wait;
    private MyTextView tv_my_bind;
    private MyTextView tv_my_good;
    private MyTextView tv_my_question;
    private MyTextView tv_my_feed;
    private MyTextView tv_my_setting;
    private MyTextView tv_login_out;
    private MyTextView tv_my_phone;
    private MyTextView tv_promote_money;
    private String phoneNumber;


    public static MyFragment newInstance() {
        return new MyFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }


    @Override
    protected void initView(View view) {
        tv_my_login = (TextView) view.findViewById(R.id.tv_my_login);
        ll_after_login = (RelativeLayout) view.findViewById(R.id.ll_after_login);
        tv_pay_now = (MyTextView) view.findViewById(R.id.tv_pay_now);
        tv_pay_wait = (MyTextView) view.findViewById(R.id.tv_pay_wait);
        tv_my_bind = (MyTextView) view.findViewById(R.id.tv_my_bind);
        tv_my_good = (MyTextView) view.findViewById(R.id.tv_my_good);
        tv_my_question = (MyTextView) view.findViewById(R.id.tv_my_question);
        tv_my_feed = (MyTextView) view.findViewById(R.id.tv_my_feed);
        tv_my_setting = (MyTextView) view.findViewById(R.id.tv_my_setting);
        tv_login_out = (MyTextView) view.findViewById(R.id.tv_login_out);
        tv_my_phone = (MyTextView) view.findViewById(R.id.tv_my_phone);
        tv_promote_money = (MyTextView) view.findViewById(R.id.tv_promote_money);

        setData();
    }


    private void setData() {
        tv_my_login.setText(Constants.isLogin ? SpUtil.getInstance().getUserInfo().getMobile() : "请登录");
        ll_after_login.setVisibility(Constants.isLogin ? View.VISIBLE : View.GONE);
        tv_login_out.setVisibility(Constants.isLogin ? View.VISIBLE : View.GONE);
    }


    @Override
    protected void addClickEvent() {
        tv_my_login.setOnClickListener(view -> checkLogin());
        tv_pay_now.setOnClickListener(view -> toPayment());
        tv_pay_wait.setOnClickListener(view -> toPayment());
        tv_my_bind.setOnClickListener((View view) -> toBind());
        tv_my_good.setOnClickListener(view -> toPayHistory());
        tv_my_question.setOnClickListener(view -> startNewActivity(QuestionActivity.class));
        tv_my_feed.setOnClickListener(view -> startNewActivity(ComplainActivity.class));
        tv_my_setting.setOnClickListener(view -> startNewActivity(SettingActivity.class));
        tv_my_phone.setOnClickListener(view -> getPhoneNumber());
        tv_login_out.setOnClickListener(view -> loginOut());
        tv_promote_money.setOnClickListener(view -> MyToast.showError(getActivity(),"暂未开放"));
    }


    //检查登录状态
    private void checkLogin() {
        if (!Constants.isLogin) {
            startActivityForResult(new Intent(getActivity(),LoginActivity.class),1);
        }
    }


    //绑定认证
    private void toBind() {
        if (!Constants.isLogin){
            checkLogin();
        }else{
            startNewActivity(BindingActivity.class);
        }
    }


    //我的订单
    private void toPayHistory() {
        if (!Constants.isLogin){
            checkLogin();
        }else{
            startNewActivity(PayHistoryActivity.class);
        }
    }


    //还款
    private void toPayment() {
        if (!Constants.isLogin){
            checkLogin();
        }else if (SpUtil.getInstance().getUserInfo().getZhuangtai().equals("2")){
           startNewActivity(PaymentActivity.class);
        }else{
            MyToast.showSuccess(getActivity(),"暂无订单");
        }
    }


    //获取客服电话
    private void getPhoneNumber() {
        showLoading("正在加载");
        OkHttpUtils.get().url(Api.getPhone).params(new HashMap<>()).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                dismissLoading();
                MyToast.showError(getActivity(),"网络异常");
            }

            @Override
            public void onResponse(String response) {
                L.e(response);
                dismissLoading();
                parsePhoneData(response);
            }
        });
    }


    private void parsePhoneData(String response) {
        PhoneBean bean=new Gson().fromJson(response,PhoneBean.class);
        if (bean.getCode()==1){
            phoneNumber=bean.getData();
            checkPermission();
        }
    }


    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
           requestPermissions(new String[]{Manifest.permission.CALL_PHONE},1);
        }else {
            call();
        }
    }


    private void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+phoneNumber));
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call();
                } else {
                    MyToast.showError(getActivity(),"您拒绝了请求");
                }
                break;
            default:
        }
    }


    //退出登陆
    private void loginOut() {
        showLoading("正在退出");
        new Handler().postDelayed(() -> {
            SpUtil.getInstance().clearUserInfo();
            SpUtil.getInstance().saveBoolean("isAutoLogin",false);
            Constants.isLogin = false;
            setData();
            dismissLoading();
            MyToast.showSuccess(getActivity(), "退出成功");
        }, 1000);
    }




    //fragment之间切换时 调用
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        setData();
        L.e(hidden+"");
    }


    //登陆返回调用
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==1&&resultCode==102){
            setData();
        }
    }
}
